from django.conf import settings
import os
import logging
from logging.handlers import TimedRotatingFileHandler


def logger_creator():
    """
    初始化logger
    :return:
    """
    if not os.path.exists(settings.LOGGING_DIR):
        os.mkdir(settings.LOGGING_DIR)

    log = logging.getLogger('base')
    log.setLevel(logging.INFO)
    std_handler = logging.StreamHandler()
    std_handler.setLevel(logging.INFO)
    file_handler = TimedRotatingFileHandler(settings.LOGGING_DIR + '/base.log', when='D', interval=1)
    file_handler.setLevel(logging.INFO)
    fmt = logging.Formatter('%(name)s %(asctime)s: %(levelname)s -- %(message)s')
    std_handler.setFormatter(fmt)
    file_handler.setFormatter(fmt)
    log.addHandler(std_handler)
    log.addHandler(file_handler)

    # initialize function called logger
    func_log = logging.getLogger('funcLogger')
    func_log.setLevel(logging.INFO)
    handler = TimedRotatingFileHandler(settings.LOGGING_DIR + '/execute.log', when='D', interval=1)
    fmt = logging.Formatter('%(name)s %(asctime)s: %(levelname)s -- %(message)s')
    handler.setFormatter(fmt)
    handler.setLevel(logging.INFO)
    func_log.addHandler(handler)

    # initialize user logger
    user_log = logging.getLogger('user')
    user_log.setLevel(logging.INFO)
    handler = TimedRotatingFileHandler(settings.LOGGING_DIR + '/user.log', when='D', interval=1)
    fmt = logging.Formatter('%(name)s %(asctime)s: %(levelname)s -- %(message)s')
    handler.setFormatter(fmt)
    handler.setLevel(logging.INFO)
    user_log.addHandler(handler)

    # initialize celery logger
    user_log = logging.getLogger('celery')
    user_log.setLevel(logging.INFO)
    handler = TimedRotatingFileHandler(settings.LOGGING_DIR + '/celery.log', when='D', interval=1)
    fmt = logging.Formatter('%(name)s %(asctime)s: %(levelname)s -- %(message)s')
    handler.setFormatter(fmt)
    handler.setLevel(logging.INFO)
    user_log.addHandler(handler)


logger_creator()
